from fastapi import FastAPI, HTTPException, Security
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security.api_key import APIKeyHeader
from starlette.status import HTTP_403_FORBIDDEN

from app.api.v1 import message, resource, crawling
from app.settings import TOKEN_LIST
from app.sql_app.database import engine
from app.sql_app.models import Base


def bootstrap() -> FastAPI:
    app = FastAPI(version='1.0.0',
                  openapi_url="/v1/openapi.json",
                  docs_url="/v1/docs",
                  redoc_url="/v1/redoc",
                  title='My API',
                  description='',
                  #   dependencies=[Depends(get_api_key)],
                  )
    # app.mount("/static", StaticFiles(directory="static"), name="static")
    register_middleware(app)
    register_routes(app)
    init_database()
    return app


async def get_api_key(api_key_header: str = Security(APIKeyHeader(name='token', auto_error=False))):
    if api_key_header in TOKEN_LIST:
        return api_key_header
    else:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
        )


def register_routes(app: FastAPI) -> None:
    prefix_version = '/v1'
    app.include_router(router=message.router, prefix=prefix_version)
    app.include_router(router=resource.router, prefix=prefix_version)
    app.include_router(router=crawling.router, prefix=prefix_version)


def register_middleware(app: FastAPI) -> None:
    # 文档地址：https://fastapi.tiangolo.com/zh/tutorial/cors/
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["*"]
    )


def init_database() -> None:
    # 创建数据表，在此之前应先创建数据库
    print('init database....')
    Base.metadata.create_all(bind=engine)
